/** @odoo-module **/

import { _t } from "@web/core/l10n/translation";

import {ControlPanel} from "@web/search/control_panel/control_panel";
import {DateTimeInput} from '@web/core/datetime/datetime_input';
import { download } from "@web/core/network/download";
import { Mutex } from "@web/core/utils/concurrency";
import {registry} from "@web/core/registry";
import {useService} from "@web/core/utils/hooks";
import { Component, onWillStart, useState, useRef } from "@odoo/owl";

const { DateTime } = luxon;

export class SOperatingStatementsComponent extends Component {
    setup() {
        this.orm = useService("orm");
        this.mutex = new Mutex();
        this.action = useService("action");
        this.date = DateTime.now().minus({ days: 1 });

        this.dayStatements = useState({});
        this.monthStatements = useState({});
        this.percentage = useState({});
        this.label = useState([]);
        this.lines = useState([]);

        onWillStart(async () => {
            await this.getOperatingStatementsValue(this.date.toFormat("yyyy-MM-dd"));
        });
    }

    async getOperatingStatementsValue() {
        const data = await this.orm.call(
            "s.operating.statements",
            "get_data_list",
            [],
            {x_date: this.date.toFormat("yyyy-MM-dd")}
        );
        this.lines.length = 0;
        this.label.length = 0
        this.lines.unshift(...data.lines)
        this.label.unshift(...data.header)
    }

    async setDate(date) {
        this.date = date;
        await this.getOperatingStatementsValue();
    }

    _onShare(){
        this.mutex.exec(() => {
            this.action.doAction('account_inherit.s_operating_statements_share_wizard_action', {
                onClose: async () => this.getOperatingStatementsValue(),
            });
        });
    }

    async onDownload() {
        const url = `/download/operating/statements/report/excel/${this.date.toFormat("yyyy-MM-dd")}`;
        const data = {};
        await download({url, data});
    }
}

SOperatingStatementsComponent.template = "account_inherit.SOperatingStatementsComponent";
SOperatingStatementsComponent.components = {
    ControlPanel,
    DateTimeInput,
};
registry.category("actions").add("s_operating_statements", SOperatingStatementsComponent);